import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  DatePicker,
  Button,
  Space,
  Statistic,
  Spin,
  Select,
  Divider,
  Table,
  message,
} from 'antd';
import {
  DownloadOutlined,
  ReloadOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  TrophyOutlined,
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { reportApi } from '@/services/api';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

const ReportsCenter: React.FC = () => {
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs(),
  ]);
  const [reportType, setReportType] = useState<'user' | 'payment'>('user');
  const [userStats, setUserStats] = useState<any>(null);
  const [paymentStats, setPaymentStats] = useState<any>(null);
  const [systemStats, setSystemStats] = useState<any>(null);
  const [userLoading, setUserLoading] = useState(false);
  const [paymentLoading, setPaymentLoading] = useState(false);

  // 获取用户统计
  const fetchUserStats = async () => {
    setUserLoading(true);
    try {
      const response = await reportApi.getUserStats([
        dateRange[0].format('YYYY-MM-DD'),
        dateRange[1].format('YYYY-MM-DD'),
      ]);
      setUserStats(response);
    } catch (error) {
      message.error('获取用户统计失败');
    } finally {
      setUserLoading(false);
    }
  };

  // 获取支付统计
  const fetchPaymentStats = async () => {
    setPaymentLoading(true);
    try {
      const response = await reportApi.getPaymentStats([
        dateRange[0].format('YYYY-MM-DD'),
        dateRange[1].format('YYYY-MM-DD'),
      ]);
      setPaymentStats(response);
    } catch (error) {
      message.error('获取支付统计失败');
    } finally {
      setPaymentLoading(false);
    }
  };

  // 获取系统统计
  const fetchSystemStats = async () => {
    try {
      const response = await reportApi.getSystemStats();
      setSystemStats(response);
    } catch (error) {
      message.error('获取系统统计失败');
    }
  };

  const loading = userLoading || paymentLoading;

  const refreshUser = fetchUserStats;
  const refreshPayment = fetchPaymentStats;
  const refreshSystem = fetchSystemStats;

  const refreshAll = () => {
    fetchUserStats();
    fetchPaymentStats();
    fetchSystemStats();
  };

  useEffect(() => {
    fetchUserStats();
    fetchPaymentStats();
  }, [dateRange]);

  useEffect(() => {
    fetchSystemStats();
  }, []);

  // 用户增长趋势图
  const getUserGrowthOption = () => ({
    title: {
      text: '用户增长趋势',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      top: 30,
    },
    xAxis: {
      type: 'category',
      data: userStats?.data?.dates || [],
      axisPointer: {
        type: 'shadow',
      },
    },
    yAxis: {
      type: 'value',
      name: '用户数',
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: userStats?.data?.values || [],
        smooth: true,
        itemStyle: {
          color: '#1890ff',
        },
        areaStyle: {
          opacity: 0.3,
        },
      },
    ],
  });

  // 支付趋势图
  const getPaymentTrendOption = () => ({
    title: {
      text: '支付趋势分析',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      top: 30,
    },
    xAxis: {
      type: 'category',
      data: paymentStats?.data?.dates || [],
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数量',
        position: 'left',
      },
      {
        type: 'value',
        name: '收入金额',
        position: 'right',
        axisLabel: {
          formatter: '¥{value}',
        },
      },
    ],
    series: [
      {
        name: '订单数量',
        type: 'bar',
        data: paymentStats?.data?.orderCounts || [],
        itemStyle: {
          color: '#52c41a',
        },
      },
      {
        name: '成功订单',
        type: 'bar',
        data: paymentStats?.data?.successCounts || [],
        itemStyle: {
          color: '#1890ff',
        },
      },
      {
        name: '收入金额',
        type: 'line',
        yAxisIndex: 1,
        data: paymentStats?.data?.revenues || [],
        smooth: true,
        itemStyle: {
          color: '#f5222d',
        },
      },
    ],
  });

  // 用户地区分布饼图
  const getUserRegionOption = () => ({
    title: {
      text: '用户地区分布',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 60,
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '60%'],
        data: userStats?.data?.regionDistribution || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  });

  // 支付方式分布饼图
  const getPaymentMethodOption = () => ({
    title: {
      text: '支付方式分布',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)<br/>金额: ¥{value}',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 60,
    },
    series: [
      {
        name: '支付方式',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '60%'],
        data: paymentStats?.data?.distribution || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  });

  // 24小时订单分布
  const getHourlyOption = () => ({
    title: {
      text: '24小时订单分布',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: Array.from({ length: 24 }, (_, i) => `${i}:00`),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '订单数量',
        type: 'bar',
        data: paymentStats?.data?.hourlyData?.map(item => item.orderCount) || [],
        itemStyle: {
          color: '#722ed1',
        },
      },
    ],
  });

  // 导出报表
  const handleExport = async (type: 'users' | 'payments') => {
    try {
      const startDate = dateRange[0].format('YYYY-MM-DD');
      const endDate = dateRange[1].format('YYYY-MM-DD');
      
      const url = `/api/reports/export/${type}?startDate=${startDate}&endDate=${endDate}`;
      const link = document.createElement('a');
      link.href = url;
      link.download = `${type === 'users' ? '用户' : '支付'}报表_${startDate}_${endDate}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      message.success('报表导出成功');
    } catch (error) {
      message.error('报表导出失败');
    }
  };

  // 排行榜数据
  const rankingColumns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 60,
      render: (rank: number) => (
        <span style={{ 
          color: rank <= 3 ? '#f5222d' : '#666',
          fontWeight: rank <= 3 ? 'bold' : 'normal' 
        }}>
          #{rank}
        </span>
      ),
    },
    {
      title: '地区',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '用户数',
      dataIndex: 'value',
      key: 'value',
      render: (value: number) => <span style={{ color: '#1890ff' }}>{value}</span>,
    },
    {
      title: '占比',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (percentage: number) => `${percentage}%`,
    },
  ];

  const rankingData = userStats?.data?.regionDistribution?.map((item, index) => ({
    key: index,
    rank: index + 1,
    name: item.name,
    value: item.value,
    percentage: ((item.value / userStats.data.totalUsers) * 100).toFixed(1),
  })) || [];

  return (
    <div style={{ padding: '24px' }}>
      {/* 控制面板 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={16} align="middle">
          <Col>
            <Space>
              <span>报表类型：</span>
              <Select
                value={reportType}
                onChange={setReportType}
                style={{ width: 120 }}
              >
                <Option value="user">用户报表</Option>
                <Option value="payment">支付报表</Option>
              </Select>
            </Space>
          </Col>
          <Col>
            <Space>
              <span>时间范围：</span>
              <RangePicker
                value={dateRange}
                onChange={(dates) => dates && setDateRange(dates)}
                format="YYYY-MM-DD"
              />
            </Space>
          </Col>
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<ReloadOutlined />}
                onClick={refreshAll}
                loading={loading}
              >
                刷新
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport(reportType === 'user' ? 'users' : 'payments')}
              >
                导出报表
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 概览统计 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日新增用户"
              value={systemStats?.data?.todayUsers || 0}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#3f8600' }}
              suffix={
                <span style={{ fontSize: '12px', color: '#666' }}>
                  增长率: {systemStats?.data?.userGrowthRate || 0}%
                </span>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日订单"
              value={systemStats?.data?.todayOrders || 0}
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#1890ff' }}
              suffix={
                <span style={{ fontSize: '12px', color: '#666' }}>
                  增长率: {systemStats?.data?.orderGrowthRate || 0}%
                </span>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日收入"
              value={systemStats?.data?.todayRevenue || 0}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={userStats?.data?.totalUsers || 0}
              prefix={<LineChartOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Spin spinning={loading}>
        {reportType === 'user' ? (
          // 用户报表
          <>
            <Row gutter={16} style={{ marginBottom: '24px' }}>
              <Col xs={24} lg={16}>
                <Card title="用户增长趋势" style={{ height: '400px' }}>
                  <ReactECharts
                    option={getUserGrowthOption()}
                    style={{ height: '320px' }}
                  />
                </Card>
              </Col>
              <Col xs={24} lg={8}>
                <Card title="地区排行榜" style={{ height: '400px' }}>
                  <Table
                    columns={rankingColumns}
                    dataSource={rankingData}
                    pagination={false}
                    size="small"
                    style={{ height: '320px' }}
                  />
                </Card>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col xs={24} lg={12}>
                <Card title="用户地区分布" style={{ height: '400px' }}>
                  <ReactECharts
                    option={getUserRegionOption()}
                    style={{ height: '320px' }}
                  />
                </Card>
              </Col>
              <Col xs={24} lg={12}>
                <Card title="用户活跃度统计">
                  <Row gutter={16}>
                    <Col span={12}>
                      <Statistic
                        title="活跃用户"
                        value={userStats?.data?.activeUsers || 0}
                        suffix="人"
                      />
                    </Col>
                    <Col span={12}>
                      <Statistic
                        title="近7天活跃"
                        value={userStats?.data?.recentActiveUsers || 0}
                        suffix="人"
                      />
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>
          </>
        ) : (
          // 支付报表
          <>
            <Row gutter={16} style={{ marginBottom: '24px' }}>
              <Col xs={24}>
                <Card title="支付趋势分析" style={{ height: '400px' }}>
                  <ReactECharts
                    option={getPaymentTrendOption()}
                    style={{ height: '320px' }}
                  />
                </Card>
              </Col>
            </Row>
            <Row gutter={16} style={{ marginBottom: '24px' }}>
              <Col xs={24} lg={12}>
                <Card title="支付方式分布" style={{ height: '400px' }}>
                  <ReactECharts
                    option={getPaymentMethodOption()}
                    style={{ height: '320px' }}
                  />
                </Card>
              </Col>
              <Col xs={24} lg={12}>
                <Card title="24小时订单分布" style={{ height: '400px' }}>
                  <ReactECharts
                    option={getHourlyOption()}
                    style={{ height: '320px' }}
                  />
                </Card>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col xs={24} sm={8}>
                <Card>
                  <Statistic
                    title="总订单数"
                    value={paymentStats?.data?.totalOrders || 0}
                    prefix={<PieChartOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={8}>
                <Card>
                  <Statistic
                    title="成功订单"
                    value={paymentStats?.data?.successOrders || 0}
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={8}>
                <Card>
                  <Statistic
                    title="总收入"
                    value={paymentStats?.data?.totalRevenue || 0}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#f5222d' }}
                  />
                </Card>
              </Col>
            </Row>
          </>
        )}
      </Spin>
    </div>
  );
};

export default ReportsCenter;